package com.icss.th.common.filter;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import com.icss.th.common.Constants;
import com.icss.th.common.config.SystemConfig;
import com.icss.th.common.util.DBUtil;
import com.icss.th.db.DBConnection;

public class ConnectionFilter implements Filter 
{
	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain filterChain) throws IOException, ServletException 
	{
		if (SystemConfig.DB_TYPE.equals(Constants.DB_TYPE.MONGODB))
		{
			filterChain.doFilter(request, response);
		}
		else
		{
			Connection conn = DBUtil.getConn();
			
			try
			{
				conn.setAutoCommit(false);
				conn.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
				
				DBConnection.setConnection(conn);
				filterChain.doFilter(request, response);
				
				conn.commit();
			}
			catch (Exception e)
			{
				if (conn != null)
				{
					try 
					{
						conn.rollback();
					} 
					catch (SQLException e1) 
					{
						e1.printStackTrace();
					}
				}
			}
			finally
			{
				if (conn != null)
				{
					try 
					{
						conn.close();
					} 
					catch (SQLException e) 
					{
						e.printStackTrace();
					}
				}
			}
		}
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException 
	{
		
	}
	
	@Override
	public void destroy() 
	{
		
	}
}
